package com.example.firstproject.controller;

import com.example.firstproject.common.WrapMapper;
import com.example.firstproject.common.Wrapper;
import com.example.firstproject.entity.User;
import com.example.firstproject.service.PhoneService;
import com.example.firstproject.service.UserService;
import com.example.firstproject.vo.PhoneCodeVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.web.context.HttpSessionSecurityContextRepository;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpSession;
import java.util.List;

@Slf4j
@RestController
@RequestMapping("/user")
public class UserController {


    @Autowired
    private AuthenticationManager authenticationManager;

    @Autowired
    private UserService userService;


    @Autowired
    private PhoneService phoneService;

    @Autowired
    private RedisTemplate redisTemplate;






    @PreAuthorize("hasRole('ROLE-admin')")
    @RequestMapping(value = "/register",method = RequestMethod.POST)
    public Wrapper<Object> userRegister(@RequestBody User user){
//        redisTemplate.opsForValue().set("username",user.getUsername());
        return WrapMapper.ok();
//        Map<String ,Object> retData = new HashMap<>();
//        if(user.getUsername().isEmpty() || user.getStudentId().isEmpty() || user.getPassword().isEmpty()){
//            retData.put("code",500);
//            retData.put("message","参数错误!");
//            return retData;
//        }else
//            return userService.userRegist(user);
//        throw new UserException("异常测试");

    }

    @RequestMapping(value = "/login",method = RequestMethod.POST)

    public Wrapper userLogin(@RequestBody User user, HttpSession session){
        UsernamePasswordAuthenticationToken unauthenticated = UsernamePasswordAuthenticationToken.
                unauthenticated(user.getUsername(),user.getPassword());
        try {
            Authentication authenticate = authenticationManager.authenticate(unauthenticated);
            SecurityContextHolder.getContext().setAuthentication(authenticate);
            session.setAttribute(HttpSessionSecurityContextRepository.SPRING_SECURITY_CONTEXT_KEY,SecurityContextHolder.getContext());
            return WrapMapper.ok();
        }catch (AuthenticationException e) {
            return WrapMapper.error();
        }
    }
//    @ResponseBody
//    public Wrapper userLogin(){
//        return WrapMapper.ok(redisTemplate.opsForValue().get("username"));
//    }
//    public Map<String,Object> userLogin(){
//        Map<String,Object> retData = new HashMap<>();
//        retData.put("massage","test");2
//        return retData;
//    }

//    public Wrapper userLogin(){
////        List<User> users = userService.getAll();
//        return WrapMapper.wrap(250,"test",users);
//    }

    @GetMapping("/user")
    public Wrapper<List<User>> getAllUser(){
        List<User> users =userService.getAllUser();
        if (users == null){
            return WrapMapper.error("查询为空");
        }else {
            for (User user : users){
                user.setPassword("***");
            }
            return WrapMapper.ok(users);
        }
    }






    @PostMapping("/testcode")
    public Wrapper testPhoneCode(@RequestBody PhoneCodeVO phoneCodeVO){
        if (phoneService.validCode(phoneCodeVO.getPhoneNum(),phoneCodeVO.getChannel(),phoneCodeVO.getUserCode())){
            return WrapMapper.ok();
        } else {
            return WrapMapper.error("验证码错误");
        }
    }


    @GetMapping("/phonecode")
    public Wrapper getPhoneCode(@RequestParam String channel,@RequestParam String phoneNum){
        return phoneService.sendCode(phoneNum,channel);
    }
}


